import axios, { AxiosError, AxiosResponseHeaders, InternalAxiosRequestConfig, RawAxiosResponseHeaders } from 'axios'
import { message } from 'ant-design-vue'
import { STORAGE_TOKEN_KEY } from '@/stores/mutation-type'
import { PageEnum } from '@/enums/pageEnum'

export type RequestError = AxiosError<{
  message?: string
  result?: any
  errorMessage?: string
}>

export interface HttpResponse<T = any> {
  /**
   * 0 表示成功 其他表示失败
   * 0 means success, others means fail
   */
  code: number
  success: boolean
  data: T
  message: string
}

export const REQUEST_TOKEN_KEY = 'Authorization'


/**
 * 获取 api 地址
 * @returns
 */
export const getApiURL = () =>
  window.location.host.toLowerCase() == 'csgp-gjp.superhrai.com'
    ? 'https://csgpapi-gjp.superhrai.com'
    : window.location.host.toLowerCase() == 'gp-gjp.superhrai.com'
      ? 'https://gpapi-gjp.superhrai.com'
      : import.meta.env.VITE_GLOB_API_URL;

const service = axios.create({
  baseURL: getApiURL(),
  timeout: 10000
})

// 异常拦截处理器
function errorHandler(error: RequestError): Promise<any> {
  if (error.response) {
    const { data = {}, status } = error.response
    // 403 无权限
    if (status === 403) {
      message.error(data?.message || '你没有操作权限')
      localStorage.removeItem(STORAGE_TOKEN_KEY)
      location.replace(PageEnum.BASE_LOGIN)
    }

    // 401 未登录/未授权
    if (status === 401) {
      message.error('请先登录')
      localStorage.removeItem(STORAGE_TOKEN_KEY)
      location.replace(PageEnum.BASE_LOGIN)
    }
    const errMsg = error.response?.data?.message || error.message
    if (errMsg) {
      message.error(errMsg)
    }
  } else {
    message.error(error.message)
  }

  console.error('Request error:', error)
  return Promise.reject(error)
}

// 请求拦截器
function requestHandler(
  config: InternalAxiosRequestConfig,
): InternalAxiosRequestConfig | Promise<InternalAxiosRequestConfig> {
  const savedToken = localStorage.getItem(STORAGE_TOKEN_KEY)
  // 如果 token 存在
  // 让每个请求携带自定义 token, 请根据实际情况修改
  if (savedToken)
    config.headers[REQUEST_TOKEN_KEY] = `Bearer ${savedToken}`

  return config
}

// 响应拦截器
function responseHandler(response: { data: HttpResponse, headers: AxiosResponseHeaders | RawAxiosResponseHeaders }) {
  const token = response.headers['access-token'] || response.headers['Access-Token']
  if (token === 'invalid_token') {
    localStorage.removeItem(STORAGE_TOKEN_KEY)
  }
  else if (token) {
    localStorage.setItem(STORAGE_TOKEN_KEY, token)
  }

  if (response.data.code === 0) {
    return response.data.data
  }

  if (response.data.message) {
    message.error(response.data.message)
  }

  console.log('response', response);
  
  // 如果是 blob 类型直接返回
  if (response.data instanceof Blob) {
    return response.data
  }

  console.error('Request error:', response.data)

  throw new Error(`Error ${response?.data?.message || '操作失败'} `)
}


service.interceptors.request.use(requestHandler,errorHandler)
service.interceptors.response.use(responseHandler,errorHandler)
export default service